package edu.zut.cs.network.exercise.practice.book.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import edu.zut.cs.network.exercise.practice.book.entity.Book;
import edu.zut.cs.network.exercise.practice.book.service.BookManager;


public class BookManagerImpl implements BookManager {

	protected Logger logger = LogManager.getLogger(this.getClass().getName());

	List<Book> bookList;
	
	Map<String, Book> map = new TreeMap();
	
	
	public void load(String data_file) {

		this.bookList = new ArrayList<Book>();
		InputStream input = BookManagerImpl.class.getResourceAsStream(data_file);
		XSSFWorkbook wb = null;
		try {
			wb = new XSSFWorkbook(input);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		XSSFSheet sheet = wb.getSheetAt(1);
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			Book book = new Book();
//			Set the system unique Id for object
			book.setId(Long.valueOf(1000 + i));
			for (int j = 0; j < row.getLastCellNum(); j++) {
				Cell cell = row.getCell(j);
				if (cell != null) {
					cell.setCellType(CellType.STRING);
					String value = row.getCell(j).getStringCellValue().trim();
					if (j == 0)
						book.setCode(value);
					if (j == 1)
						book.setName(value);
					if (j == 2)
						book.setPrice(value);

				}
			}
			logger.info(" book_" + i + "is :" + book);
			this.bookList.add(book);
		}
		logger.info("size of book list is :" + this.bookList.size());
	}
	
	public Book findByName(String name) {
		// TODO Auto-generated method stub
		return null;
	}

}
